from typing import Dict, Optional, Tuple
from enum import Enum

class KFSType(Enum):
    EMPTY = "empty"        # 空方块
    R1_KFS = "r1_kfs"      # R1武术秘籍（比赛logo）
    R2_KFS = "r2_kfs"      # R2武术秘籍（甲骨文字）
    FAKE_KFS = "fake_kfs"  # 假秘籍（随机字体文字）

class RobotR2:
    """R2机器人控制类（纯接口实现）"""
    
    def __init__(self):
        """
        初始化机器人状态
        """
        self.position: Optional[Tuple[int, int]] = None  # (x,y)坐标
        self.direction: str = 'north'  # 当前朝向：north/east/south/west
        self.time_consumed: int = 0     # 运动耗时（单位：时间步）
        self.steps_moved: int = 0       # 移动步数
        self.kfs_collected: int = 0     # 已收集KFS数量
        self._pick_cost = [1, 3, 7, 15] # 拾取KFS的时间成本
        
    def execute_command(self, command: str) -> bool:
        """
        执行机器人控制指令
        @
        :param command: 指令类型 ('forward', 'backward', 'turn_left', 'turn_right')
        :return: 是否执行成功
        """
        if command == 'forward':
            return self._move_forward()
        elif command == 'backward':
            return self._move_backward()
        elif command == 'turn_left':
            return self._turn_left()
        elif command == 'turn_right':
            return self._turn_right()
        return False
    
    def can_pick_kfs(self, front_block: KFSType) -> bool:
        """
        检查是否可以拾取前方KFS
        @
        :param front_block: 前方方块的KFS类型（由外部传入）
        :return: 是否可拾取
        """
        # 只能拾取正前方的R2_KFS
        return (front_block == KFSType.R2_KFS)
    
    def pick_kfs(self, front_b: KFSType) -> None:
        """
        执行拾取操作（需外部确保can_pick_kfs返回True）
        @
        :param front_b: 前方方块的KFS类型
        :return: 本次拾取消耗的时间
        """
        if self.can_pick_kfs(front_b):
            cost = self._pick_cost[self.kfs_collected]
            self.kfs_collected += 1
            self.time_consumed += cost
            print(f"R2 picked a KFS, cost {cost} time steps")
        else:
            cost = self._pick_cost[self.kfs_collected]
            self.time_consumed += cost
            print("R2 cannot pick KFS, cost {cost} time steps")
        
    
    def get_position(self) -> Optional[Tuple[int, int]]:
        """获取当前坐标"""
        return self.position
    
    def get_direction(self) -> str:
        """获取当前朝向"""
        return self.direction
    
    def get_status(self) -> Dict:
        """获取机器人状态"""
        return {
            'position': self.position,
            'direction': self.direction,
            'time_consumed': self.time_consumed,
            'steps_moved': self.steps_moved,
            'kfs_collected': self.kfs_collected
        }
    
    def reset(self):
        """重置机器人状态"""
        self.position = None
        self.direction = 'north'
        self.time_consumed = 0
        self.steps_moved = 0
        self.kfs_collected = 0

    ### 运动指令 ###
    def _move_forward(self) -> bool:
        """向前移动一格"""
        if self.position is None:
            return False
        
        # 计算新位置
        x, y = self.position
        if self.direction == 'north':
            y += 1
        elif self.direction == 'east':
            x += 1
        elif self.direction == 'south':
            y -= 1
        elif self.direction == 'west':
            x -= 1
        
        self.position = (x, y)
        self.steps_moved += 1
        self.time_consumed += 1
        return True
    
    def _move_backward(self) -> bool:
        """向后移动一格"""
        if self.position is None:
            return False
        
        # 计算新位置
        x, y = self.position
        if self.direction == 'north':
            y -= 1
        elif self.direction == 'east':
            x -= 1
        elif self.direction == 'south':
            y += 1
        elif self.direction == 'west':
            x += 1
        
        self.position = (x, y)
        self.steps_moved += 1
        self.time_consumed += 1
        return True
    
    def _turn_left(self) -> bool:
        """向左转90度"""
        directions = ['north', 'west', 'south', 'east']
        current_idx = directions.index(self.direction)
        self.direction = directions[(current_idx + 1) % 4]
        self.time_consumed += 1
        return True
    
    def _turn_right(self) -> bool:
        """向右转90度"""
        directions = ['north', 'east', 'south', 'west']
        current_idx = directions.index(self.direction)
        self.direction = directions[(current_idx + 1) % 4]
        self.time_consumed += 1
        return True